package com.example.cemenghuii.controller;

import com.example.cemenghuii.dto.ApiResponse;
import com.example.cemenghuii.entity.MeetingRegistration;
import com.example.cemenghuii.service.WeChatService;
import com.example.cemenghuii.service.NewsService;
import com.example.cemenghuii.service.CourseService;
import com.example.cemenghuii.service.MeetingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/mini")
@CrossOrigin(origins = "*")
public class MiniProgramController {

    @Autowired
    private WeChatService weChatService;

    @Autowired
    private NewsService newsService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private MeetingService meetingService;

    /**
     * 微信小程序登录
     */
    @PostMapping("/login")
    public ApiResponse<Map<String, Object>> miniLogin(@RequestBody Map<String, String> loginData) {
        try {
            String code = loginData.get("code");
            if (code == null || code.isEmpty()) {
                return ApiResponse.badRequest("code不能为空");
            }

            Map<String, Object> result = weChatService.code2Session(code);
            if ((Boolean) result.get("success")) {
                return ApiResponse.success("登录成功", result);
            } else {
                return ApiResponse.error("登录失败：" + result.get("errmsg"));
            }
        } catch (Exception e) {
            return ApiResponse.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 获取首页数据
     */
    @GetMapping("/home")
    public ApiResponse<Map<String, Object>> getHomeData() {
        try {
            // 获取最新新闻（前5条）
            Map<String, Object> latestNews = newsService.getPublishedNewsList(null, 1, 5);

            // 获取热门课程（前5条）
            Map<String, Object> popularCourses = courseService.getPublishedCourseList(null, 1, 5);

            // 获取即将开始的会议（前3条）
            Map<String, Object> upcomingMeetings = meetingService.getUpcomingMeetings(1, 3);

            Map<String, Object> result = Map.of(
                    "latestNews", latestNews.get("list"),
                    "popularCourses", popularCourses.get("list"),
                    "upcomingMeetings", upcomingMeetings.get("list")
            );

            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("获取首页数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取行业动态列表（小程序端）
     */
    @GetMapping("/news/list")
    public ApiResponse<Map<String, Object>> getNewsForMini(@RequestParam(required = false) String keyword,
                                                           @RequestParam(defaultValue = "1") Integer page,
                                                           @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = newsService.getPublishedNewsList(keyword, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取行业动态详情（小程序端）
     */
    @GetMapping("/news/{id}")
    public ApiResponse<Object> getNewsDetailForMini(@PathVariable Long id) {
        try {
            Object news = newsService.getNewsDetail(id, true);
            if (news == null) {
                return ApiResponse.notFound("新闻不存在");
            }
            return ApiResponse.success(news);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取课程列表（小程序端）
     */
    @GetMapping("/course/list")
    public ApiResponse<Map<String, Object>> getCoursesForMini(@RequestParam(required = false) String keyword,
                                                              @RequestParam(defaultValue = "1") Integer page,
                                                              @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = courseService.getPublishedCourseList(keyword, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取课程详情（小程序端）
     */
    @GetMapping("/course/{id}")
    public ApiResponse<Object> getCourseDetailForMini(@PathVariable Long id) {
        try {
            Object course = courseService.getCourseDetail(id, true);
            if (course == null) {
                return ApiResponse.notFound("课程不存在");
            }
            return ApiResponse.success(course);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取会议列表（小程序端）
     */
    @GetMapping("/meeting/list")
    public ApiResponse<Map<String, Object>> getMeetingsForMini(@RequestParam(required = false) String keyword,
                                                               @RequestParam(required = false) String meetingType,
                                                               @RequestParam(defaultValue = "1") Integer page,
                                                               @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = meetingService.getPublishedMeetingList(keyword, meetingType, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据类型获取会议列表（小程序端）
     */
    @GetMapping("/meeting/type/{meetingType}")
    public ApiResponse<Map<String, Object>> getMeetingsByTypeForMini(@PathVariable String meetingType,
                                                                     @RequestParam(defaultValue = "1") Integer page,
                                                                     @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = meetingService.getMeetingByType(meetingType, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取会议详情（小程序端）
     */
    @GetMapping("/meeting/{id}")
    public ApiResponse<Object> getMeetingDetailForMini(@PathVariable Long id) {
        try {
            Object meeting = meetingService.getMeetingById(id);
            if (meeting == null) {
                return ApiResponse.notFound("会议不存在");
            }
            return ApiResponse.success(meeting);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 会议报名（小程序端）
     */
    @PostMapping("/meeting/{id}/register")
    public ApiResponse<Void> registerMeetingForMini(@PathVariable Long id,
                                                    @RequestBody MeetingRegistration registration) {
        try {
            registration.setMeetingId(id);
            boolean success = meetingService.registerMeeting(registration);
            if (success) {
                return ApiResponse.success("报名成功");
            } else {
                return ApiResponse.error("报名失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 取消会议报名（小程序端）
     */
    @DeleteMapping("/meeting/{id}/register")
    public ApiResponse<Void> cancelMeetingRegistrationForMini(@PathVariable Long id,
                                                              @RequestParam String openId) {
        try {
            boolean success = meetingService.cancelRegistration(id, openId);
            if (success) {
                return ApiResponse.success("取消报名成功");
            } else {
                return ApiResponse.error("取消报名失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 检查用户是否已报名会议（小程序端）
     */
    @GetMapping("/meeting/{id}/check-registration")
    public ApiResponse<Map<String, Object>> checkMeetingRegistrationForMini(@PathVariable Long id,
                                                                            @RequestParam String openId) {
        try {
            boolean registered = meetingService.checkUserRegistration(id, openId);
            Map<String, Object> result = Map.of("registered", registered);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 搜索内容（小程序端）
     */
    @GetMapping("/search")
    public ApiResponse<Map<String, Object>> searchForMini(@RequestParam String keyword,
                                                          @RequestParam(defaultValue = "all") String type,
                                                          @RequestParam(defaultValue = "1") Integer page,
                                                          @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = Map.of();

            switch (type) {
                case "news":
                    result = newsService.getPublishedNewsList(keyword, page, pageSize);
                    break;
                case "course":
                    result = courseService.getPublishedCourseList(keyword, page, pageSize);
                    break;
                case "meeting":
                    result = meetingService.getPublishedMeetingList(keyword, null, page, pageSize);
                    break;
                case "all":
                default:
                    // 搜索所有类型的内容
                    Map<String, Object> newsResult = newsService.getPublishedNewsList(keyword, 1, 5);
                    Map<String, Object> courseResult = courseService.getPublishedCourseList(keyword, 1, 5);
                    Map<String, Object> meetingResult = meetingService.getPublishedMeetingList(keyword, null, 1, 5);

                    result = Map.of(
                            "news", newsResult.get("list"),
                            "courses", courseResult.get("list"),
                            "meetings", meetingResult.get("list")
                    );
                    break;
            }

            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("搜索失败：" + e.getMessage());
        }
    }

    /**
     * 获取热门内容（小程序端）
     */
    @GetMapping("/hot")
    public ApiResponse<Map<String, Object>> getHotContentForMini() {
        try {
            // 获取热门新闻（按浏览量排序，前10条）
            Map<String, Object> hotNews = newsService.getPublishedNewsList(null, 1, 10);

            // 获取热门课程（按浏览量排序，前10条）
            Map<String, Object> hotCourses = courseService.getPublishedCourseList(null, 1, 10);

            // 获取热门会议（按报名人数排序，前10条）
            Map<String, Object> hotMeetings = meetingService.getPublishedMeetingList(null, null, 1, 10);

            Map<String, Object> result = Map.of(
                    "hotNews", hotNews.get("list"),
                    "hotCourses", hotCourses.get("list"),
                    "hotMeetings", hotMeetings.get("list")
            );

            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("获取热门内容失败：" + e.getMessage());
        }
    }

    /**
     * 获取分类数据（小程序端）
     */
    @GetMapping("/categories")
    public ApiResponse<Map<String, Object>> getCategoriesForMini() {
        try {
            // 会议类型分类
            String[] meetingTypes = {"会议研讨", "标准定制", "技术培训", "工具研发", "公益行动"};

            Map<String, Object> result = Map.of(
                    "meetingTypes", meetingTypes
            );

            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("获取分类数据失败：" + e.getMessage());
        }
    }
}